/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.controller.market;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.waleychain.exchange.consumer.controller.BaseController;
import cn.waleychain.exchange.core.constant.DDIC;
import cn.waleychain.exchange.core.entity.PageInfo;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.result.DefaultResult;
import cn.waleychain.exchange.core.result.IBaseResult;
import cn.waleychain.exchange.core.utils.BigDecimalUtils;
import cn.waleychain.exchange.core.utils.SequenceUtils;
import cn.waleychain.exchange.core.vaildate.VaildateHelper;
import cn.waleychain.exchange.feign.MarketServiceFeign;
import cn.waleychain.exchange.model.Market;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(description = "市场相关接口")
@RestController
@RequestMapping("api/v1/market")
public class MarketController extends BaseController {

	private static final Logger mLog = LoggerFactory.getLogger(MarketController.class);
	
	@Autowired
	private MarketServiceFeign marketFeign;
	
	@RequestMapping(value = "/fetchPageList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "分页获取市场列表", notes = "分页获取市场列表，URL: http://{ip}:{port}/{projectName}/api/v1/market/fetchPageList", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchPageList(
			@ApiParam(value = "名称", required = false) @RequestParam(required = false) String name,
			@ApiParam(value = "标题", required = false) @RequestParam(required = false) String title,
			@ApiParam(value = "状态（0 禁用 1 启用）", required = false) @RequestParam(required = false) Integer status,
			@ApiParam(value = "交易区域", required = false) @RequestParam(required = false) String transAreaId,
			@ApiParam(value = "每次查询多少条数据", required = true) @RequestParam(required = true, defaultValue = "-1") Integer showCount, 
			@ApiParam(value = "当前查询页", required = true) @RequestParam(required = true, defaultValue = "1") Integer currentPage, 
			@RequestHeader String Authorization) throws Exception {

		try {

			PageInfo<Market> page = marketFeign.fetchMarketPageList(name, title, status, transAreaId, showCount, currentPage);

			return DefaultResult.buildSuccessResult(page);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "分页获取市场列表");
		}

		return DefaultResult.buildSuccessResult();
	}
	
	@RequestMapping(value = "/fetchListByCache", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "从缓存中获取所有交易市场列表", notes = "从缓存中获取所有交易市场列表，URL: http://{ip}:{port}/{projectName}/api/v1/market/fetchListByCache", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchListByCache(
			@RequestHeader String Authorization) throws Exception {

		try {

			return DefaultResult.buildSuccessResult();
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "从缓存中获取所有交易市场列表");
		}

		return DefaultResult.buildSuccessResult();
	}
	
	@RequestMapping(value = "/new", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "新增市场", notes = "新增市场，URL: http://{ip}:{port}/{projectName}/api/v1/market/new", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult addMarketInfo (
			@ApiParam(value = "买方币种ID", required = true) @RequestParam Long buyCoinId,
			@ApiParam(value = "卖方市场ID", required = true) @RequestParam Long sellCoinId,
			@ApiParam(value = "交易周期", required = true) @RequestParam String tradeWeek,
			@ApiParam(value = "交易时间", required = true) @RequestParam String tradeTime,
			@ApiParam(value = "发行价格", required = true) @RequestParam BigDecimal openPrice,
			@ApiParam(value = "最小买入量", required = true) @RequestParam BigDecimal buyMin,
			@ApiParam(value = "最大买入量", required = true) @RequestParam BigDecimal buyMax,
			@ApiParam(value = "最小卖出量", required = true) @RequestParam BigDecimal sellMin,
			@ApiParam(value = "最大卖出量", required = true) @RequestParam BigDecimal sellMax,
			@ApiParam(value = "买入手续费率", required = true) @RequestParam BigDecimal feeBuy,
			@ApiParam(value = "卖出手续费率", required = true) @RequestParam BigDecimal feeSell,
			@ApiParam(value = "单笔最小数量", required = true) @RequestParam BigDecimal tradeMin,
			@ApiParam(value = "单笔最大数量", required = true) @RequestParam BigDecimal tradeMax,
			@ApiParam(value = "涨幅", required = true) @RequestParam BigDecimal zhang,
			@ApiParam(value = "跌幅", required = true) @RequestParam BigDecimal die,
			@ApiParam(value = "排序", required = true) @RequestParam Integer sorting,
			@ApiParam(value = "状态（0 禁用 1 启用）", required = true) @RequestParam Integer status,
			@ApiParam(value = "交易区域", required = true) @RequestParam String transactionAreaId,
			@RequestHeader String Authorization) throws Exception {

		try {
			
			VaildateHelper.vaildateIntParams(status, "状态", DDIC.MarketStatus.MARKET_STATUS_0.id, DDIC.MarketStatus.MARKET_STATUS_1.id);
			
			Market market = new Market();
			market.setMarketId(SequenceUtils.generateDefaultSerialNum());
			market.setBuyCoinId(buyCoinId);
			market.setSellCoinId(sellCoinId);
			market.setOpenPrice(openPrice);
			market.setBuyMin(buyMin);
			market.setBuyMax(buyMax);
			market.setSellMin(sellMin);
			market.setSellMax(sellMax);
			market.setFeeBuy(feeBuy);
			market.setFeeSell(feeSell);
			market.setTradeMin(tradeMin);
			market.setTradeMax(tradeMax);
			market.setTradeWeek(tradeWeek);
			market.setTradeTime(tradeTime);
			market.setZhang(zhang);
			market.setDie(die);
			market.setAlertPriceRate(BigDecimalUtils.genInitValue());
			market.setStatus(status);
			market.setTransactionAreaId(transactionAreaId);
			market.setCreateTime(new Date());
			market.setUpdateTime(new Date());
			market.setSorting(sorting);

			boolean result = marketFeign.addMarket(market);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "新增市场");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/info", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "获取市场信息", notes = "获取市场信息，URL: http://{ip}:{port}/{projectName}/api/v1/market/info", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchMarketInfo(
			@ApiParam(value = "标识ID", required = true) @RequestParam Long marketId, 
			@RequestHeader String Authorization) throws Exception {

		try {

			Market market = marketFeign.fetchMarketInfoById(marketId);

			return DefaultResult.buildSuccessResult(market);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "获取市场信息");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/setMarketStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "设置币种状态", notes = "设置币种状态，URL: http://{ip}:{port}/{projectName}/api/v1/market/setMarketStatus", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult setMarketStatus(
			@ApiParam(value = "标识ID", required = true) @RequestParam Long marketId, 
			@ApiParam(value = "状态（0 禁用 1 启用）", required = true) @RequestParam Integer status, 
			@RequestHeader String Authorization) throws Exception {

		try {

			boolean result = marketFeign.setMarketStatus(marketId, status);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "设置币种状态");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/modify", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "编辑市场信息", notes = "编辑市场信息，URL: http://{ip}:{port}/{projectName}/api/v1/market/modify", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult modify (
			@ApiParam(value = "标识ID", required = true) @RequestParam Long marketId,
			@ApiParam(value = "交易周期", required = true) @RequestParam String tradeWeek,
			@ApiParam(value = "交易时间", required = true) @RequestParam String tradeTime,
			@ApiParam(value = "发行价格", required = true) @RequestParam BigDecimal openPrice,
			@ApiParam(value = "最小买入量", required = true) @RequestParam BigDecimal buyMin,
			@ApiParam(value = "最大买入量", required = true) @RequestParam BigDecimal buyMax,
			@ApiParam(value = "最小卖出量", required = true) @RequestParam BigDecimal sellMin,
			@ApiParam(value = "最大卖出量", required = true) @RequestParam BigDecimal sellMax,
			@ApiParam(value = "买入手续费率", required = true) @RequestParam BigDecimal feeBuy,
			@ApiParam(value = "卖出手续费率", required = true) @RequestParam BigDecimal feeSell,
			@ApiParam(value = "单笔最小数量", required = true) @RequestParam BigDecimal tradeMin,
			@ApiParam(value = "单笔最大数量", required = true) @RequestParam BigDecimal tradeMax,
			@ApiParam(value = "涨幅", required = true) @RequestParam BigDecimal zhang,
			@ApiParam(value = "跌幅", required = true) @RequestParam BigDecimal die,
			@ApiParam(value = "排序", required = true) @RequestParam Integer sorting,
			@ApiParam(value = "状态（0 禁用 1 启用）", required = true) @RequestParam Integer status,
			@RequestHeader String Authorization) throws Exception {

		try {

			Market market = new Market();
			market.setMarketId(marketId);
			market.setOpenPrice(openPrice);
			market.setBuyMin(buyMin);
			market.setBuyMax(buyMax);
			market.setSellMin(sellMin);
			market.setSellMax(sellMax);
			market.setFeeBuy(feeBuy);
			market.setFeeSell(feeSell);
			market.setTradeMin(tradeMin);
			market.setTradeMax(tradeMax);
			market.setTradeWeek(tradeWeek);
			market.setTradeTime(tradeTime);
			market.setStatus(status);
			market.setZhang(zhang);
			market.setDie(die);
			market.setUpdateTime(new Date());
			market.setSorting(sorting);
			
			boolean result = marketFeign.updateMarketInfo(market);

			return DefaultResult.buildResult(result);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "编辑市场信息");
		}

		return DefaultResult.buildFailedResult();
	}
	
	@RequestMapping(value = "/fetchMarketListByCoinId", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "通过币种获取可用的交易市场列表", notes = "通过币种获取可用的交易市场列表，URL: http://{ip}:{port}/{projectName}/api/v1/market/fetchMarketListByCoinId", httpMethod = "GET", response = DefaultResult.class)
	public IBaseResult fetchMarketListByCoinId(
			@ApiParam(value = "币种标识ID", required = true) @RequestParam Long coinId, 
			@RequestHeader String Authorization) throws Exception {

		try {

			List<Market> marketList = marketFeign.fetchMarketListByCoinId(coinId);

			return DefaultResult.buildSuccessResult(marketList);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "通过币种获取可用的交易市场列表");
		}

		return DefaultResult.buildFailedResult();
	}
	
}
